#import "SMTradeViewController.h"
#import <Masonry/Masonry.h>
#import "SMTradeListViewController.h"          // 子列表页
#import "../../Views/Components/SMTopTabBar.h" // 顶部文字+下划线控件
#import <QMUIKit/QMUIPopupMenuView.h>          // 悬浮菜单（QMUIKit）

@interface SMTradeViewController () <SMTopTabBarDelegate, UIPageViewControllerDataSource, UIPageViewControllerDelegate>
@property(nonatomic, strong) SMTopTabBar *tabBar;
@property(nonatomic, strong) UIPageViewController *pager;
@property(nonatomic, strong) NSArray<UIViewController *> *pages;
@property(nonatomic, strong) UIButton *fab;
@property (nonatomic, strong) QMUIPopupMenuView *publishMenu;

@end

@implementation SMTradeViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"买卖";
    self.view.backgroundColor = UIColor.systemGroupedBackgroundColor;

    // 顶部：文字+下划线
    _tabBar = [[SMTopTabBar alloc] initWithTitles:@[@"供应", @"求购"]];
    _tabBar.delegate = self;
    [self.view addSubview:_tabBar];
    [_tabBar mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];

    // 下方：PageView 两个子控制器
    SMTradeListViewController *supply = [[SMTradeListViewController alloc] initWithType:SMTradeListTypeSupply];
    SMTradeListViewController *demand = [[SMTradeListViewController alloc] initWithType:SMTradeListTypeDemand];
    self.pages = @[supply, demand];

    _pager = [[UIPageViewController alloc] initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                                            navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                                          options:nil];
    _pager.dataSource = self; _pager.delegate = self;
    [_pager setViewControllers:@[self.pages.firstObject] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [self addChildViewController:_pager];
    [self.view addSubview:_pager.view];
    [_pager didMoveToParentViewController:self];
    [_pager.view mas_makeConstraints:^(MASConstraintMaker *make){
        make.top.equalTo(self.tabBar.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
    }];

    // 右下角悬浮按钮 + 菜单
    _fab = [UIButton buttonWithType:UIButtonTypeSystem];
    if (@available(iOS 13.0, *)) { [_fab setImage:[UIImage systemImageNamed:@"plus"] forState:UIControlStateNormal]; }
    _fab.tintColor = UIColor.whiteColor;
    _fab.backgroundColor = [UIColor colorWithRed:0.23 green:0.56 blue:0.96 alpha:1.0];
    _fab.layer.cornerRadius = 28;
    _fab.layer.shadowColor = [UIColor blackColor].CGColor;
    _fab.layer.shadowOpacity = 0.2;
    _fab.layer.shadowRadius = 6;
    _fab.layer.shadowOffset = CGSizeMake(0, 4);
    [self.view addSubview:_fab];
    [_fab mas_makeConstraints:^(MASConstraintMaker *make){
        make.width.height.mas_equalTo(56);
        make.right.equalTo(self.view).offset(-18);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-18);
    }];
    [_fab addTarget:self action:@selector(showPublishMenu) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 顶部标签交互
- (void)topTabBarDidSelectIndex:(NSInteger)index {
    NSInteger current = [self.pages indexOfObject:self.pager.viewControllers.firstObject];
    if (current == NSNotFound || current == index) return;
    UIPageViewControllerNavigationDirection dir = (index > current) ? UIPageViewControllerNavigationDirectionForward : UIPageViewControllerNavigationDirectionReverse;
    [self.pager setViewControllers:@[self.pages[index]] direction:dir animated:YES completion:nil];
}

#pragma mark - PageViewController 数据源/联动
- (UIViewController *)pageViewController:(UIPageViewController *)p viewControllerBeforeViewController:(UIViewController *)vc {
    NSUInteger idx = [self.pages indexOfObject:vc];
    if (idx==NSNotFound || idx==0) return nil;
    return self.pages[idx-1];
}
- (UIViewController *)pageViewController:(UIPageViewController *)p viewControllerAfterViewController:(UIViewController *)vc {
    NSUInteger idx = [self.pages indexOfObject:vc];
    if (idx==NSNotFound || idx+1>=self.pages.count) return nil;
    return self.pages[idx+1];
}
- (void)pageViewController:(UIPageViewController *)p didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (!completed) return;
    UIViewController *cur = p.viewControllers.firstObject;
    NSInteger idx = [self.pages indexOfObject:cur];
    [self.tabBar setSelectedIndex:idx animated:YES];
}

- (void)showPublishMenu {
    if (self.publishMenu.isShowing) {
        [self.publishMenu hideWithAnimated:YES];
        self.publishMenu = nil;
        return;
    }

    QMUIPopupMenuView *menu = [[QMUIPopupMenuView alloc] init];
    menu.automaticallyHidesWhenUserTap = YES;      // 窗口模式支持点击遮罩自动收起
    menu.maskViewBackgroundColor = UIColor.clearColor;
    menu.itemHeight = 48;
    menu.cornerRadius = 12;

    __weak typeof(self) weakSelf = self;
    UIImage *up=nil,*down=nil;
    if (@available(iOS 13.0, *)) {
        up   = [UIImage systemImageNamed:@"arrow.up.circle"];
        down = [UIImage systemImageNamed:@"arrow.down.circle"];
    }

    menu.items = @[
        [QMUIPopupMenuButtonItem itemWithImage:up   title:@"发布出售"
          handler:^(__kindof QMUIPopupMenuButtonItem * _Nonnull item) { [weakSelf handlePublishType:YES]; }],
        [QMUIPopupMenuButtonItem itemWithImage:down title:@"发布求购"
          handler:^(__kindof QMUIPopupMenuButtonItem * _Nonnull item) { [weakSelf handlePublishType:NO]; }]
    ];

    // ⭐️关键：告诉 QMUI 以哪个视图为锚点
    menu.sourceView = self.view;          // 会自动计算 sourceRect

    self.publishMenu = menu;
    [menu showWithAnimated:YES];         // 会创建 popupWindow 并根据 sourceView 定位
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.publishMenu.isShowing) {
        [self.publishMenu hideWithAnimated:NO];
        self.publishMenu = nil;
    }
}


- (void)handlePublishType:(BOOL)isSell {
    // TODO: 跳转到发布表单页（标题/图片/城市/价格/描述，配 TZImagePickerController）
    UIAlertController *ac=[UIAlertController alertControllerWithTitle:(isSell?@"发布出售":@"发布求购")
                                                              message:@"这里进入发布表单页"
                                                       preferredStyle:UIAlertControllerStyleAlert];
    [ac addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:ac animated:YES completion:nil];
}
@end
